<?php
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
include '../../include/dbFunctions.php';
include ("../../include/function.php");
include ("../../include/image_slider.php");
require ("../../include/class.phpmailer.php");

$array = array('volunteer_firstname', 'volunteer_surname', 'volunteer_email', 'volunteer_mobile', 'volunteer_password', 'volunteer_profession');
// check user input
$empty = check_empty($array);
$mail = check_email('volunteer_email');
$email = $_POST['volunteer_email'];
$duplicate_email = check_duplicate('volunteer_email', 'volunteer', $email);
// get input data from volunteer Registration
$volunteer_firstname = htmlspecialchars($_POST['volunteer_firstname'], ENT_QUOTES);
$volunteer_familyname = htmlspecialchars($_POST['volunteer_surname'], ENT_QUOTES);
$name = $volunteer_firstname . " " . $volunteer_familyname;
$volunteer_salutation = $_POST['volunteer_salutation'];
$volunteer_gender = $_POST['volunteer_gender'];
$sponsor_id = $_POST['sponsor_id'];
$volunteer_experience = htmlspecialchars($_POST['volunteer_experience'], ENT_QUOTES);
$volunteer_profession = htmlspecialchars($_POST['volunteer_profession'], ENT_QUOTES);
$volunteer_mobile = $_POST['volunteer_mobile'];
$volunteer_timeslot = $_POST['preferred_timeslot'];
$volunteer_reference = $_POST['volunteer_reference'];
$volunteer_email = htmlspecialchars($_POST['volunteer_email'], ENT_QUOTES);
$volunteer_password = htmlspecialchars($_POST['volunteer_password'], ENT_QUOTES);

$volunteer_password = sha1($volunteer_password);

if (isset($_POST['volunteer_office'])) {
    $volunteer_office = $_POST['volunteer_office'];
} else {
    $volunteer_office = '';
}

if ($_FILES['uploadfile']['name'] != '') {

    function findexts($filename) {
        $filename = strtolower($filename);
        $exts = explode(".", $filename);
        $n = count($exts) - 1;
        $exts = $exts[$n];
        return $exts;
    }

    $ext = findexts($_FILES['uploadfile']['name']);
    $ran = rand(1, 100000);
    $ran2 = $ran . ".";
    $target = "../../admin/upload/cv/";
    $target = $target . $ran2 . $ext;

    move_uploaded_file($_FILES['uploadfile']['tmp_name'], $target);
    $volunteer_cv = $ran2 . $ext;
    /*
     * $target_path = "../../admin/upload/cv/";

      $volunteer_cv = $_FILES['uploadfile']['name'];
      $target_path = $target_path . basename($_FILES['uploadfile']['name']);
      move_uploaded_file($_FILES['uploadfile']['tmp_name'], $target_path);
     * 
     */
}

//$created_date = date("y-m-j H:i:s ");

$activationKey = mt_rand() . mt_rand() . mt_rand() . mt_rand() . mt_rand();

if ($_FILES['uploadfile']['name'] !='') {
$insert_volunteer = "INSERT INTO volunteer (volunteer_firstname,volunteer_surname,volunteer_salutation,volunteer_gender, volunteer_email,volunteer_mobile, volunteer_office, volunteer_status, sponsor_id, volunteer_profession, volunteer_reference,volunteer_experience, volunteer_password, volunteer_cv )
                             VALUES ('$volunteer_firstname','$volunteer_familyname' ,'$volunteer_salutation','$volunteer_gender','$volunteer_email', '$volunteer_mobile', '$volunteer_office', '$activationKey', $sponsor_id, '$volunteer_profession', '$volunteer_reference', '$volunteer_experience', '$volunteer_password', '$volunteer_cv'  )";
}
else{
    $insert_volunteer = "INSERT INTO volunteer (volunteer_firstname,volunteer_surname,volunteer_salutation,volunteer_gender, volunteer_email,volunteer_mobile, volunteer_office, volunteer_status, sponsor_id, volunteer_profession, volunteer_reference,volunteer_experience, volunteer_password)
                             VALUES ('$volunteer_firstname','$volunteer_familyname' ,'$volunteer_salutation','$volunteer_gender','$volunteer_email', '$volunteer_mobile', '$volunteer_office', '$activationKey', $sponsor_id, '$volunteer_profession', '$volunteer_reference', '$volunteer_experience', '$volunteer_password')";
}
$insert_volunteer = executeQuery($insert_volunteer);

$volunteer_id = "SELECT * FROM volunteer WHERE volunteer_email = '$volunteer_email'";
$volunteer_id = executeSelectQuery($volunteer_id);
$volunteer_id = $volunteer_id[0]['volunteer_id'];
if ($volunteer_timeslot != '2') {
    $insert_time = "INSERT INTO time_preference (volunteer_id, time_id) VALUES ($volunteer_id, '$volunteer_timeslot' )";
    $insert_time = executeQuery($insert_time);
} else {
    $insert_time1 = "INSERT INTO time_preference (volunteer_id, time_id) VALUES ($volunteer_id,'0' )";
    $insert_time1 = executeQuery($insert_time1);

    $insert_time2 = "INSERT INTO time_preference (volunteer_id, time_id) VALUES ($volunteer_id,'1' )";
    $insert_time2 = executeQuery($insert_time2);
}

/* Insert new volunteer information
  $sql = "INSERT INTO volunteer (volunteer_name,volunteer_salutation,volunteer_gender, volunteer_email, volunteer_password,volunteer_address,volunteer_mobile,volunteer_office, volunteer_remarks,volunteer_status, sponsor_id, created_date, last_modified)
  VALUES ('$volunteer_name','$volunteer_salutation' , '$volunteer_gender','$volunteer_email', '$volunteer_password','$volunteer_address','$volunteer_mobile','$volunteer_office','$volunteer_remarks', '$activationKey',$sponsor_id, '$created_date', '$created_date')";
  $insert = executeQuery($sql);

  // get new volunteer id
  $query = "SELECT volunteer_id FROM volunteer WHERE volunteer_email = '$volunteer_email' ";
  $id = executeSelectQuery($query);
 */

//select and set final location choices base on business rule
$location = array();
$loc = "SELECT location_id FROM location";
$loc = executeSelectQuery($loc);
for ($i = 0; $i < count($loc); $i++) {
    $location[] = $loc[$i]['location_id'];
}

if (isset($_POST['location'])) {
    $location_array = $_POST['location'];
} else {
    $location_array = $location;
}
//select and set final leducation choices base on business rule
$education = array();
$edu = "SELECT education_id FROM education";
$edu = executeSelectQuery($edu);
for ($i = 0; $i < count($edu); $i++) {
    $education[] = $edu[$i]['education_id'];
}

if (isset($_POST['education'])) {
    $education_array = $_POST['education'];
} else {
    $education_array = $education;
}


// if user submit registration information
if ($_POST['form_submitted'] == '1') {
    //cheking input condition
    if (empty($empty) && empty($mail) && empty($duplicate_emai)) {
        // can insert volunteer detials?
        if ($insert_volunteer == 1) {
            $total = 0;
            $true = 0;
            $false = 1;
            //insert volunteer location
            
            
            
            for ($i = 0; $i < count($location_array); $i++) {
                $location = $location_array[$i];
               
                $query = "INSERT INTO location_preference (volunteer_id,location_id) VALUES ($volunteer_id,$location)";
                $insertLocation = executeQuery($query);

                if ($insertLocation != 0) {
                    $total = $total + $true;
                } else {
                    $total = $total + $false;
                }
            }
            
            // insert volunteer education
            for ($i = 0; $i < count($education_array); $i++) {
                $education = $education_array[$i];

                $query = "INSERT INTO education_preference (volunteer_id,education_id) VALUES ($volunteer_id,$education)";
                $insertEducation = executeQuery($query);
                if ($insertEducation != 0) {
                    $total = $total + $true;
                } else {
                    $total = $total + $false;
                }
            }
          
            if ($total == 0) {
                $to = $email;
                $subject = "JA Registration Activation Email";
                $message = <<<HERE
Welcome to JA Singapore. Thank you for your registration to the JA Scheduling System.

Please click on the link below NOW to active your account:
\rhttp://scheduler.ja.org.sg/volunteer/registration/volunteerVerifyRegistration.php?$activationKey\r\r

If you cannot run the link, please copy and paste it to your favourite browser and run.

Thank you for your support of JA Programs.

Best regards,
Ng. Hau Yee (Ms.)
Director
Junior Achievement Singapore



* This is an auto-generated email. Please do not reply
Any questions, please email hauyee.ng@ja.org

* It is an auto-generated email. Please do not reply
Any question, please email hauyee.ng@ja.org


HERE;
                $headers = "From: hauyee.ng@ja.org" . "\r\n" .
                        "Reply-To: hauyee.ng@ja.org" . "\r\n" .
                        "X-Mailer: PHP/" . phpversion();

                $sendresult = mail($to, $subject, $message, $headers);





                if ($sendresult) {

                    $message = "An email has been sent to " . $_POST['volunteer_email'] . " with an activation key. Please check your mail to complete registration.";
                } else {
                    $message = "Error! Message was not sent. Please contact <a href ='mailto:hauyee.ng@ja.org'><font color='#0000FF'>JA Singapore Director Ms. Ng Hau Yee </font></a>  for further enquiry<br/>";
                    $message.= 'Mailer error: ' . $mail->ErrorInfo;
                    $message.="<input type='button'class='form-back' value='' onclick='history.go(-1)'/>";
                }
            } else {
                $message = 'Error:  Problem during insert education  preference/ location preference. Please try again.';
                $message.="<input type='button'class='form-back' value='' onclick='history.go(-1)'/>";
            }
        } else {
            $message = 'Error with inserting volunteer';
            $message.="<input type='button'class='form-back' value='' onclick='history.go(-1)'/>";
        }
    } else {
        $message = "Your register is not successful because of following reasons:<br/>";
        $message.= $mail . "<br>";
        $message.= $duplicate_email . "<br>";
        for ($i = 0; $i < count($empty); $i++) {
            $message.= $empty[$i] . "<br>";
        }
        $message.="<input type='button' class='form-back' value='' onclick='history.go(-1)'/>";
    }
} else {
    ##User isn't registering, check verify code and change activation code to null, status to activated on success

    $queryString = $_SERVER['QUERY_STRING'];

    $query = "SELECT * FROM volunteer";
    $result = executeSelectQuery("SELECT * FROM volunteer");

    if ($result) {

        for ($i = 0; $i < count($result); $i++) {
            if ($queryString == $result[$i]['volunteer_status']) {

                $id = $result[$i]['volunteer_id'];
                //Update volunteer status (active account)
                $sql = "UPDATE volunteer SET volunteer_status='active' WHERE volunteer_id = $id";
                $update = executeQuery($sql);
                $name = "SELECT volunteer_firstname, volunteer_surname FROM volunteer WHERE volunteer_id = $id";
                $name = executeSelectQuery($name);
                $final_name = $name[0]['volunteer_firstname'].' '. $name[0]['volunteer_surname'];
                if ($update == 1) {

                    $headers = "From: hauyee.ng@ja.org" . "\r\n" .
                            "Reply-To: hauyee.ng@ja.org" . "\r\n" .
                            "X-Mailer: PHP/" . phpversion();


                    $to_admin = "hauyee.ja@gmail.com ";
                    $subject_admin = "New volunteer registered!";
                    $message_admin = "New volunteer name: ". $final_name." had successfully registered. Please check your system for more details. ";
                     $message_admin.= "Admin site: http://scheduler.ja.org.sg/admin";
                    mail($to_admin, $subject_admin, $message_admin, $headers);

                    $message = "Congratulations! " . $final_name. " is now the proud new owner of an JA scheduling System account. ";
                    $message.="Please click to this link to go to the main page:
                       <a href = 'http://scheduler.ja.org.sg/include/home/homepage.php'> Main Page </a>
                       ";
                } else {
                    echo "update error.";
                }
            } else {
              
            }
        }
    } else {
        echo "no result";
    }
}
?>
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Junior Achievement Singapore</title>
        <link href="../../media/css/styles.css" rel="stylesheet" type="text/css" />
        <script type="text/javascript" language="javascript" src="../../media/js/jquery/jquery-1.6.1.min.js"></script>
        <script type="text/javascript" src="../../media/js/jquery/image_slider.js"></script>
        <!-- Custom jquery scripts -->
        <script src="../../media/js/jquery/custom_jquery.js" type="text/javascript"></script>
    </head>
    <body>
        <script>
            var timeout    = 700;
            var closetimer = 0;
            var ddmenuitem = 0;

            function jsddm_open()
            {  jsddm_canceltimer();
                jsddm_close();
                ddmenuitem = $(this).find('ul').css('visibility', 'visible');}

            function jsddm_close()
            {  if(ddmenuitem) ddmenuitem.css('visibility', 'hidden');}

            function jsddm_timer()
            {  closetimer = window.setTimeout(jsddm_close, timeout);}

            function jsddm_canceltimer()
            {  if(closetimer)
                {  window.clearTimeout(closetimer);
                    closetimer = null;}}

            $(document).ready(function()
            {  $('#navigation > li').bind('mouseover', jsddm_open)
                $('#navigation > li').bind('mouseout',  jsddm_timer)});

            document.onclick = jsddm_close;

        </script>
        <div id="container"><!--CONTAINER STARTS-->
            <div id="navigation">
                <li><a href="../../include/home/homepage.php">HOME</a></li>
                <li><a href="mailto:admin@jasingapore.com">CONTACT</a></li>
                <li><a href="http://jaworldwide.org/">ABOUT JA</a></li>
                <li><a href="http://jascheduling.lefora.com/">FEEDBACK</a></li>
                <li><a href="../../guide/guide_menu.php">HELP</a></li>

            </div>
            <div id="title"><!--TITLE STARTS-->
            </div><!--TITLE ENDS-->
            <div id="featured"><!--FEATURED AREA STARTS-->

                <div class="featured-image"><!--FEATURED IMAGE STARTS-->
                    <img alt="Featured Image" src="../../media/images/featured_image.png" />
                </div><!--FEATURED IMAGE ENDS-->
                <div class="featured-text"><!--FEATURED TEXT STARTS-->

                    <h2>Welcome to JA Singapore</h2>
                    <p>Junior Achievement programs help prepare young people for the real world by showing them how to generate wealth and effectively manage it, how to create jobs which make their communities more robust, and how to apply entrepreneurial thinking to the workplace. <a href="http://www.jaworldwide.org/">Read More... </a></p>

                </div><!--FEATURED TEXT ENDS-->

            </div><!--FEATURED AREA ENDS-->

<?php
custom_login();
?>
            <div id="left-content"><!--RIGHT CONTENT STARTS-->

                <div class="left-top"><!--RIGHT CONTENT BOX TOP-->
                </div><!--RIGHT CONTENT BOX TOP ENDS-->

                <div class="left-middle"><!--RIGHT CONTENT BOX MIDDLE-->

<?php
echo "<br/><br/><br/><br/><br/><center><p class='pmain'>$message</p></center><br/><br/><br/><br/><br/><br/><br/><br/>";
?>

                </div><!--RIGHT CONTENT BOX MIDDLE ENDS-->

                <div class="left-bottom"><!--RIGHT CONTENT BOX BOTTOM-->
                </div><!--RIGHT CONTENT BOX BOTTOM ENDS-->
            </div><!--RIGHT CONTENT ENDS-->
        </div><!--CONTAINER ENDS-->
        <div id="footer"><!--FOOTER STARTS-->
            <p>Copyright &copy; Junior Achievement Singapore | All Rights Reserved</p>
        </div><!--FOOTER ENDS-->
    </body>
</html>